import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Widget textFieldBgWidget(
    bool ifShowClear, double width, double height, TextField textfield) {
  return Stack(
    children: <Widget>[
      Container(
        width: width,
        height: height,
        color: Colors.yellow,
      ),
      Positioned(
        left: 5,
        right: 20,
        top: 5,
        bottom: 5,
        child: textfield,
      ),
      Positioned(
          left: width - 35,
          right: 5,
          top: 5,
          bottom: 5,
          child: Visibility(
            visible: ifShowClear,
            child: Container(
              child: Icon(Icons.cancel),
            ),
          )),
    ],
  );
}

///自带删除的ITextField
typedef void ITextFieldCallBack(String content);

enum ITextInputType {
  text,
  multiline,
  number,
  phone,
  datetime,
  emailAddress,
  url,
  password
}

class ITextField extends StatefulWidget {
  final ITextInputType keyboardType;
  final int maxLines;
  final int maxLength;
  final String hintText;
  final TextStyle hintStyle;
  final ITextFieldCallBack fieldCallBack;
  final Icon deleteIcon;
  final InputBorder inputBorder;
  final Widget prefixIcon;
  final TextStyle textStyle;
  final FormFieldValidator<String> validator;

  ITextField({
    Key key,
    ITextInputType keyboardType: ITextInputType.text,
    this.maxLines = 1,
    this.maxLength,
    this.hintText,
    this.hintStyle,
    this.fieldCallBack,
    this.deleteIcon,
    this.inputBorder,
    this.textStyle,
    this.prefixIcon,
    this.validator,
  })  : assert(maxLines == null || maxLines > 0),
        assert(maxLength == null || maxLength > 0),
        keyboardType = maxLines == 1 ? keyboardType : ITextInputType.multiline,
        super(key: key);

  @override
  State<StatefulWidget> createState() => _ITextFieldState();
}

class _ITextFieldState extends State<ITextField> {
  String _inputText = "";
  bool _hasdeleteIcon = false;
  bool _isNumber = false;
  bool _isPassword = false;
  FocusNode _focusNode1 = FocusNode();

  ///输入类型
  TextInputType _getTextInputType() {
    switch (widget.keyboardType) {
      case ITextInputType.text:
        return TextInputType.text;
      case ITextInputType.multiline:
        return TextInputType.multiline;
      case ITextInputType.number:
        _isNumber = true;
        return TextInputType.number;
      case ITextInputType.phone:
        _isNumber = true;
        return TextInputType.phone;
      case ITextInputType.datetime:
        return TextInputType.datetime;
      case ITextInputType.emailAddress:
        return TextInputType.emailAddress;
      case ITextInputType.url:
        return TextInputType.url;
      case ITextInputType.password:
        _isPassword = true;
        return TextInputType.text;
    }
  }

  ///输入范围
  List<TextInputFormatter> _getTextInputFormatter() {
    return _isNumber
        ? <TextInputFormatter>[
            WhitelistingTextInputFormatter.digitsOnly,
          ]
        : null;
  }

  @override
  Widget build(BuildContext context) {

     _focusNode1.addListener(() {
      // TextField has lost focus
      print(_focusNode1.hasFocus ? '获的焦点111111' : '失去焦点11111');
      setState(() {
        _hasdeleteIcon = _focusNode1.hasFocus;
      });
    });
    TextEditingController _controller = new TextEditingController.fromValue(
        TextEditingValue(
            text: _inputText,
            selection: new TextSelection.fromPosition(TextPosition(
                affinity: TextAffinity.downstream,
                offset: _inputText.length))));
    TextField textField = new TextField(
      controller: _controller,
      focusNode: _focusNode1,
      decoration: InputDecoration(
          hintStyle: widget.hintStyle,
          counterStyle: TextStyle(color: Colors.white),
          hintText: widget.hintText,
          border: widget.inputBorder != null
              ? widget.inputBorder
              : UnderlineInputBorder(),
          fillColor: Colors.transparent,
          filled: true,
          prefixIcon: widget.prefixIcon,
          suffixIcon: Visibility(
            visible: _focusNode1.hasFocus,
            child: new Container(
              width: 20.0,
              height: 20.0,
              child: new IconButton(
                alignment: Alignment.center,
                padding: const EdgeInsets.all(0.0),
                iconSize: 18.0,
                icon: widget.deleteIcon != null
                    ? widget.deleteIcon
                    : Icon(Icons.cancel),
                onPressed: () {
                  setState(() {
                    _inputText = "";
                    widget.fieldCallBack(_inputText);
                  });
                },
              ),
            ),
          )
          // _hasdeleteIcon
          //     ?
          //     : new Text(""),
          ),
      onChanged: (str) {
        setState(() {
          _inputText = str;
          widget.fieldCallBack(_inputText);
        });
      },
      keyboardType: _getTextInputType(),
      maxLength: widget.maxLength,
      maxLines: widget.maxLines,
      inputFormatters: _getTextInputFormatter(),
      style: widget.textStyle,
      obscureText: _isPassword,
    );
    return textField;
  }
}


class LoginTextField extends TextField {
  LoginTextField({
    Key key,
    String text,

    String placeholder, 

    /// prefix icon 
    bool prefixIconSelected,
    String prefixIconNormalImageName,
    String prefixIconSelectedImageName,

    bool autofocus = false,
    bool obscureText = false,
    TextInputType keyboardType,
    TextEditingController controller,
    bool showClear = false,
    TextInputAction textInputAction,
    FocusNode focusNode,
    ValueChanged<String> onSubmitted,
  }) : super(
    key: key,
    autofocus: autofocus,
    obscureText: obscureText,
    style: TextStyle(color: Colors.black, fontSize: 17.0),
    decoration: InputDecoration(
      contentPadding: EdgeInsets.all(0.0),
      //labelText: "用户名",
      hintText: placeholder,
      //prefixIcon: Icon(Icons.person),
      prefixIcon: new Image.asset(
        !prefixIconSelected ? prefixIconNormalImageName :prefixIconSelectedImageName,
        width: 14.0,
        height: 15.0,
      ),
      // suffixIcon: !showClear ? null : clearButtonWithOnPressed(controller.clear),
      enabledBorder: loginTextFieldDecorationBorder(),
      focusedBorder: loginTextFieldDecorationBorder(),
    ),
    keyboardType: keyboardType,
    controller: controller,
    textInputAction: textInputAction,
    focusNode: focusNode,
    onSubmitted: onSubmitted
    );
}

/// selected Image
class SelectedImage extends Image {
  SelectedImage({
    Key key,
    bool selected,
    String normalImageName,
    String selectedImageName,
  }) :super (
      key: key,
      image: AssetImage(!selected ? normalImageName :selectedImageName)
  );
}


/// 文本框border
InputBorder loginTextFieldDecorationBorder() {
  return new OutlineInputBorder(
      borderSide: new BorderSide(color: Color(0xffd2d2d2), width: 0.6),
      borderRadius: new BorderRadius.circular(6.0)
  );
}